package top.easyblog.core.util;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import top.easyblog.common.exception.BusinessException;
import top.easyblog.common.response.ShortlinkResultCode;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.function.Supplier;

/**
 * @author: frank.huang
 * @date: 2023-12-19 20:10
 */
public final class AssertUtil {
    private AssertUtil() {
    }


    public static void isTrue(boolean expression, String message) {
        if (!expression) {
            throw new BusinessException(ShortlinkResultCode.INVALID_PARAMS, message);
        }
    }

    public static void isTrue(boolean expression, Supplier<String> messageSupplier) {
        if (!expression) {
            throw new BusinessException(ShortlinkResultCode.INVALID_PARAMS, nullSafeGet(messageSupplier));
        }
    }


    public static void isNull(Object object, String message) {
        if (object != null) {
            throw new BusinessException(ShortlinkResultCode.INVALID_PARAMS, message);
        }
    }


    public static Object notNull(Object object, String message) {
        if (object == null) {
            throw new BusinessException(ShortlinkResultCode.INVALID_PARAMS, message);
        }

        return object;
    }

    public static Object notNull(Object object, Supplier<String> messageSupplier) {
        if (object == null) {
            throw new BusinessException(ShortlinkResultCode.INVALID_PARAMS, nullSafeGet(messageSupplier));
        }

        return object;
    }


    public static String hasLength(String text, String message) {
        if (!StringUtils.hasLength(text)) {
            throw new BusinessException(ShortlinkResultCode.INVALID_PARAMS, message);
        }

        return text;
    }

    public static String hasLength(String text, Supplier<String> messageSupplier) {
        if (!StringUtils.hasLength(text)) {
            throw new BusinessException(ShortlinkResultCode.INVALID_PARAMS, nullSafeGet(messageSupplier));
        }

        return text;
    }


    public static Collection<?> noNullElements(Collection<?> collection, String message) {
        if (collection != null) {
            Iterator iterator = collection.iterator();

            while (iterator.hasNext()) {
                Object element = iterator.next();
                if (element == null) {
                    throw new BusinessException(ShortlinkResultCode.INVALID_PARAMS, message);
                }
            }
        }

        return collection;
    }


    public static Map<?, ?> notEmpty(Map<?, ?> map, String message) {
        if (CollectionUtils.isEmpty(map)) {
            throw new BusinessException(ShortlinkResultCode.INVALID_PARAMS, message);
        }

        return map;
    }


    private static String nullSafeGet(Supplier<String> messageSupplier) {
        return messageSupplier != null ? (String) messageSupplier.get() : null;
    }
}
